package io.alvin.ch03;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * CyclicBarrier Demo
 *
 * 注：第86行代码，会引发CyclicBarrier的两类异常（1个InterruptedException和9个BrokenBarrierException）。
 *
 * Created by Alvin on 2017/7/7.
 */
public class CyclicBarrierDemo {

    public static class Soldier implements Runnable {

        private String soldier;
        private final CyclicBarrier cyclic;

        Soldier(CyclicBarrier cyclic, String soldierName) {
            this.cyclic = cyclic;
            this.soldier = soldierName;
        }

        @Override
        public void run() {
            try {
                //等待所有士兵集齐
                cyclic.await();

                doWork();

                //等待所有士兵完成操作
                cyclic.await();
            } catch (InterruptedException e) { //可以处理中断
                e.printStackTrace();
            } catch (BrokenBarrierException e) { // 表示当前CyclicBarrier已经破损，无法等齐所有线程
                e.printStackTrace();
            }
        }

        void doWork() {
            try {
                Thread.sleep(Math.abs(new Random().nextInt()%10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(soldier + ":任务完成");
        }
    }

    public static class BarrierRun implements Runnable {

        boolean flag;
        int N;

        public BarrierRun(boolean flag, int n) {
            this.flag = flag;
            N = n;
        }

        @Override
        public void run() {
            if (flag) {
                System.out.println("司令：【士兵" + N + "个，任务完成！】");
            } else {
                System.out.println("司令：【士兵" + N + "个，集合完毕！】");
                flag = true; // 标记进入第二次循环
            }
        }
    }

    public static void main(String[] args) {
        final int N = 10;
        Thread[] allSoldier = new Thread[N];
        boolean flag = false;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(N, new BarrierRun(flag, N));

        // 设置屏障点，主要是为了执行这个方法
        System.out.println("集合队伍！");
        for (int i = 0; i < N; ++i) {
            System.out.println("士兵"+i+" 报到！");
            allSoldier[i] = new Thread(new Soldier(cyclicBarrier, "士兵"+i));
            allSoldier[i].start();
            if (i == 5) {
                // 可以造成CyclicBarrier异常
                allSoldier[i].interrupt();
            }
        }
    }

}
